package org.pan.controller;

import com.google.common.base.Preconditions;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import org.pan.Controller;
import org.pan.GuiceFx;
import org.pan.ResizeHelper;
import org.pan.bean.LoginUser;
import org.pan.service.SystemService;

import java.net.URL;
import java.util.ResourceBundle;

@Controller(fxml = "/fxml/login.fxml")
public class LoginController implements Initializable {
    public TextField username;
    public TextField password;
    public Label error;

    @Inject
    private Stage stage;
    @Inject
    private EventBus eventBus;
    @Inject
    private SystemService systemService;


    public void login(ActionEvent actionEvent) {
        try {
            String usernameText = username.getText();
            String passwordText = password.getText();
            Preconditions.checkArgument(StringUtils.isNotBlank(usernameText));
            Preconditions.checkArgument(StringUtils.isNotBlank(passwordText));
            Preconditions.checkArgument(usernameText.equals(passwordText));
            LoginUser loginUser = systemService.login(usernameText, passwordText);

            Preconditions.checkNotNull(loginUser);
            stage.setScene(new Scene(GuiceFx.load(LayoutController.class)));
            stage.centerOnScreen();
            ResizeHelper.addResizeListener(stage);
        } catch (Exception e) {
            error.setText("用户名密码不匹配");
        }
    }

    public void exit(ActionEvent actionEvent) {
        System.exit(1);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        eventBus.register(this);
    }
}

